<?php
/**
 * Created by PhpStorm.
 * Author：D H
 * Date: 2017/7/3
 * Time: 10:06
 */

namespace app\api\logic;

use think\Db;
use tool\Common;
use think\Request;
use Cache\RedisDB;
use think\Cache;

class User extends Base{

    //加密密码
    public static function createPassword($password = '') {
        return md5($password.'123456789987654321');
    }

    //生成随机字符串
    public static function createStr($length = 32)
    {
        $chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
        $str = '';
        for ( $i = 0; $i < $length; $i++ ) {
            $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
        }
        return md5($str);
    }

    //账号密码登录
    public function login()
    {
        $arr = [
            'account' => $this->data['account'],
            'password' => self::createPassword($this->data['password'])
        ];
        $result = Db::name('operator')->where($arr)->find();
        if (!$result) {
            return Common::rm(-2,'账号或密码错误');
        }
        $token = self::createStr();
        $tokenExpireTime = THINK_START_TIME + 86400*30;
        Db::name('operator')->where($arr)->update([
            'token' => $token,
            'tokenExpireTime' => $tokenExpireTime
        ]);
        $user = Db::name('operator')->where($arr)->field('token,photo,name')->find();
        return Common::rm(1,'登录成功',[
            'userInfo' => $user
        ]);
    }

    //第三方微信登录             --------------------------
    public function WeChatLogin(){

    }

    //退出
    public function logout()
    {
        $userID = $this->getUserID();
        $result = Db::name('user')->where('id',$userID)->update(['token' => '']);
        if ($result == 1) {
            return Common::rm(1,'退出成功');
        } else {
            return Common::rm(-2,'退出失败');
        }
    }

    //修改头像
    public function replacePhoto(){
        //测试数据
       /* $arr = '{
        "photo":"http://qianchengwl.cn/2d012.JPG"
        }';
       $data = json_decode($arr,true);*/
       $data = $this->data;
       Db::name('operator')->where('id',$this->getUserID())->update($data['photo']);
       return Common::rm(1,'操作成功');
    }

    //修改名称
    public function replaceName(){
        //测试数据
        /* $arr = '{
         "Name":"http://qianchengwl.cn/2d012.JPG"
         }';
        $data = json_decode($arr,true);*/
        $data = $this->data;
        Db::name('operator')->where('id',$this->getUserID())->update($data['Name']);
      return  Common::rm(1,'操作成功');
    }

    //修改密码
    public function replacePassword(){
         //验证规则
        $check = $this->check(__FUNCTION__);
        if($check['code'] != 1) {
            return $check;
        }

        $data = self::createPassword($this->data['password']);
        Db::name('operator')->where('id',$this->getUserID())->update(['password' => $data]);
        return Common::rm(1,'操作成功');
    }

    //用户注册                ---------------------------------------
    public function register(){

    }

    //找回密码
    public function backPassword(){

    }

    //添加收藏
    public function addCollect(){

    }

    //用户注册，发送验证码（验证码为四位）
    public function sendMessageForBandUser()
    {
        /*$arr = '{
          "mobile":"15968808705"
        }';
        $this->data = json_decode($arr,true);*/
        $mobile = Db::name('operator')->where('account',$this->data['mobile'])->find();
        //验证手机号码
        if ($mobile) {
            return Common::rm(-4,'当前用户已存在，请登录');
        }
        if(Cache::has('bandUser')) {
            $cache = Cache::get('bandUser');
            //验证时间
            $timeSpan = THINK_START_TIME - $cache['time'];
            if($timeSpan < 30) {
                return Common::rm(-3, '请过'.(int)(30 - $timeSpan).'秒之后重新发送！');
            }
            //验证次数
            if($cache['times'] > 5) {
                return Common::rm(-4, '当前发送次数过多，请过5分钟之后尝试继续发送');
            }
        }
        $mobilecode = rand(1000, 9999);
        $cache = [
            'auth'=>md5($this->data['mobile'].$mobilecode),
            //发送验证码时间
            'time'=>THINK_START_TIME,
            //发送验证码次数
            'times'=>1
        ];
        Cache::set('bandUser', $cache, 300);
        //第三步，发送短信
        $text = '【谦程网络】您的验证码是' . $mobilecode . '。如非本人操作，请忽略本短信';
        $result = Common::sendSMS($this->data['mobile'], $text);
        //第四步，返回
        if($result === 0) {
            $cache['times']++;
            $cache['time'] = THINK_START_TIME;
            Cache::set('bandUser-', $cache, 300);
            return Common::rm(1, '验证码已经发送！');
        }
        return Common::rm(-2, '操作失败！', $result);
    }

}